﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MINERP.OldSamllPicPrint.View;
using MINERP.MODEL.SmallPic;
using MINERP.BLL.SmallPic;
using MINERP.OldSamllPicPrint.Forms;
using System.Windows.Forms;
using System.IO;
using MINERP.MODEL.FoundationModel;
using System.Data;
using FastReport;
using FastReport.Utils;
using MINERP.OldSamllPicPrint.Properties;
using MINERP.BLL.OldSmallPic;

namespace MINERP.OldSamllPicPrint.Presenter
{
    public class MainPresenter
    {
        private IMainView _view;
        private List<ProductView> _curTaskList;
        private OldSamllPicMainBLL _bll;

        public MainPresenter(IMainView view)
        {

            _view = view;
            _bll = new OldSamllPicMainBLL();
            IniFrmView();
            string strReprotDir = _bll.GetReportDir();
            if (string.IsNullOrEmpty(strReprotDir) || strReprotDir == "")
            {
                MessageBox.Show("还未设置导出目录请先设置！");
            }
            else
            {
                DataTransfer.StrReportDir = strReprotDir;
            }

        }

        internal void IniFrmView()//初始化界面内容
        {
            int curTechid = _view.CurTechId;
            if (curTechid == 0)
            {
                curTechid = 12;//默认值为12
            }
            if (curTechid != 0)
            {
                _curTaskList = _bll.GetCurTaskList(curTechid);
                _view.ShowTaskList(_curTaskList);
            }
        }

        internal void ExPortPic()//导出照片到指定的目录
        {
            if (string.IsNullOrEmpty(DataTransfer.StrReportDir))
            {
                MessageBox.Show("没有设定扩印机的默认文件夹，请先设定！");
                return;
            }

            if (!Directory.Exists(DataTransfer.StrReportDir))
            {
                MessageBox.Show("请确认扩印机的默认文件夹能正常访问，然后再试！");
                return;
            }

            StartExport();
        }

        public delegate void ShowMsg(string photoPath, bool isSus);
        public static event ShowMsg ShowMsgEvent;

        private void StartExport()//开始导出图片
        {
            if (_curTaskList == null)
            {
                MessageBox.Show("没有选择任何产品！");
                return;
            }
            List<ProductView> selectProduct = _curTaskList.Where(o => o.IsSelect).ToList();
            if (selectProduct.Count < 1)
            {
                MessageBox.Show("没有选择任何产品！");
                return;
            }

            FrmMovePic frmMsg = new FrmMovePic();
            frmMsg.TotalPhotoNum = selectProduct.Sum(o => o.Photos.Count);
            frmMsg.Show();

            foreach (var oiTask in selectProduct)
            {
                string strTarGetOrderPath = DataTransfer.StrReportDir + "\\" + oiTask.OrderCode + "_" + oiTask.ShopName + "_" + oiTask.OrderName;
                if (!Directory.Exists(strTarGetOrderPath))
                {
                    Directory.CreateDirectory(strTarGetOrderPath);

                }
                else
                {
                    if (DialogResult.No == MessageBox.Show("该定单产品的目录已存在是否要覆盖？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                    {
                        continue;
                    }
                }

                //然后移图片
                bool CopyOk = MovePic(oiTask.Photos, strTarGetOrderPath);
                oiTask.Status = 1;
            }
            frmMsg.Close();
            MessageBox.Show("导出成功！");
        }

        private bool MovePic(List<PhotoInfo_Info> photoS, string tarGetPath)//当sourPath中的照片移动到tarGetPath目录中，只包括一层的jpg.tif
        {
            bool result = true;
            foreach (var photo in photoS)
            {
                FileInfo fi = new FileInfo(photo.PicPath);
                try
                {
                    string newName = fi.Name.Substring(0, fi.Name.IndexOf(fi.Extension));
                    if (File.Exists(tarGetPath + "\\" + fi.Name))
                    {
                        fi.CopyTo(tarGetPath + "\\" + newName + Guid.NewGuid().ToString() + fi.Extension, true);
                    }
                    else
                    {
                        fi.CopyTo(tarGetPath + "\\" + fi.Name, true);
                    }
                   
                   
                    if (DataTransfer.MoveByPhotoNum)
                    {
                        for (int i = 1; i < photo.TotalNum; i++)
                        {            
                            fi.CopyTo(tarGetPath + "\\" + newName + i.ToString() + fi.Extension, true);
                        }
                    }
                }
                catch (Exception)
                {
                    ShowMsgEvent(photo.PicPath, false);
                    MessageBox.Show("移动图片" + fi.FullName + "时出错，请手动拷贝!");
                    result = false;

                    break;
                }
                ShowMsgEvent(photo.PicPath, true);

            }
            return result;
        }

        internal void PrintSelectTask()//打印选定的产品（连打）
        {
            if (_curTaskList == null)
            {
                MessageBox.Show("没有选择任何产品！");
                return;
            }
            List<ProductView> selectProduct = _curTaskList.Where(o => o.IsSelect).ToList();
            if (selectProduct.Count < 1)
            {
                MessageBox.Show("没有选择任何产品！");
                return;
            }

            foreach (var oiTask in selectProduct)
            {
                PrintOItask(oiTask);
                //PrintTicket(_bll.GetOrderInfoToPrintTicket(oiTask.OrderProductId, _printerInfo.PrinterID));
            }
        }


        internal void CompleteSelectTask()//完成选定的产品列表
        {
            if (_curTaskList == null)
            {
                MessageBox.Show("没有选择任何产品！");
                return;
            }
            List<ProductView> selectProduct = _curTaskList.Where(o => o.IsSelect).ToList();
            if (selectProduct.Count < 1)
            {
                MessageBox.Show("没有选择任何产品！");
                return;
            }

            if (DialogResult.Yes == MessageBox.Show("确认要完成选中的产品？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                foreach (var oiTask in selectProduct)
                {
                    if (oiTask.Status != 1)
                    {
                        if (DialogResult.Yes == MessageBox.Show("产品：" + oiTask.OrderPath + "在本此操作中未导出过片，是否要完成?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                        {
                            if (_view.CurTechId<1)
                            {
                                MessageBox.Show("当前前品" + oiTask.OrderProductId + "当前的节点为：" + _view.CurTechId);
                            }                        
                            _bll.CompleteTask(oiTask, _view.CurTechId, _view.OperUid);
                        }
                        else
                        {
                            continue;
                        }
                    }

                    _bll.CompleteTask(oiTask, _view.CurTechId, _view.OperUid);

                }

                IniFrmView();
                MessageBox.Show("操作成功！");
            }
        }
        /// <summary>
        /// 打印小票
        /// </summary>
        /// <param name="gInfo"></param>
        public void PrintTicket(MINERP.MODEL.SmallPic.OrderInfo_Info orderInfo)
        {
            try
            {
                Report report = new Report();
                report.Load(Application.StartupPath + "\\Report\\扩印小票.frx");
                //分为二部分：1、照片尺寸归类信息，用TABLE格式
                DataTable dt = new DataTable("PhotoSize");
                dt.Columns.Add("Size", typeof(string));
                dt.Columns.Add("Num", typeof(int));

                foreach (var item in orderInfo.PhotoInfoList.GroupBy(p => p.PhtotoSizeInch + "(in) (" + p.PhotoSizeCm + ")cm").ToList())
                {
                    dt.Rows.Add(new object[] { item.Key, item.Count() });
                }

                //dt.WriteXml(@"D:\分片小票数据.xml", XmlWriteMode.WriteSchema);
                //2、相应的头信息

                report.RegisterData(dt, "PhotoSize");
                //dt.WriteXml("");

                //gInfo.OrderInfo.CtmName = gInfo.OrderInfo.CtmName.Replace('[', '(').Replace(']', ')');
                //gInfo.OrderInfo.OrderProductName = gInfo.OrderInfo.OrderProductName.Replace('[', '(').Replace(']', ')');
                //gInfo.OrderInfo.Remark = gInfo.OrderInfo.Remark.Replace('[', '(').Replace(']', ')');

                //fasrReport.SetParameterValue("shopName", gInfo.OrderInfo.ShopName);
                report.SetParameterValue("orderBarCode", orderInfo.OrderProductId.ToString());
                report.SetParameterValue("ctmName", orderInfo.CtmName);
                report.SetParameterValue("orderProductName", orderInfo.OrderProductName);
                //fasrReport.SetParameterValue("nextTechName", nextTechName);
                report.SetParameterValue("orderRemark", orderInfo.Remark);
                //fasrReport.SetParameterValue("gridName", gInfo.GridBaseInfo.GridName);
                report.SetParameterValue("priorityRemark", orderInfo.Priority >= 6 ? "急件" + orderInfo.Priority.ToString() : "");
                report.SetParameterValue("photoNumAndTotalNum", orderInfo.PhotoNumAndTotalNum);

                report.PrintSettings.ShowDialog = true;

                report.Print();
            }
            catch
            {

            }
        }

        internal void FullSelect()
        {
            if (_curTaskList != null && _curTaskList.Count > 0)
            {
                _curTaskList.ForEach(t => t.IsSelect = true);
            }
            _view.ShowTaskList(_curTaskList);
        }

        internal void ReSelect()
        {
            if (_curTaskList != null && _curTaskList.Count > 0)
            {
                _curTaskList.ForEach(t => t.IsSelect = !t.IsSelect);
            }
            _view.ShowTaskList(_curTaskList);
        }

        internal int PrintOrderInfo(string strCode)
        {
            int ret = 0;
            ProductView pv = _bll.GetProductViewByCode(strCode);
            if (pv != null)
            {
                PrintOItask(pv);
                //PrintTicket(_bll.GetOrderInfoToPrintTicket(pv.OrderProductId, _printerInfo.PrinterID));
            }
            else
            {
                MessageBox.Show("错误的产品编号！");
                ret = 1;
            }
            return ret;
        }


        private void PrintOItask(ProductView product)//打印该产品
        {
            Report report = new Report();
            DataTable table = new DataTable();
            table.TableName = "Table";
            table.Columns.Add("OrderProductName");
            table.Columns.Add("CtmName");
            table.Columns.Add("OrderProductCode");
            table.Columns.Add("shopName");
            table.Columns.Add("PageNum");
            table.Columns.Add("PaperType");
            table.Columns.Add("PaperFace");
            table.Columns.Add("KeyWord");//关键字，如果产品备注里有淋膜的就写入淋膜，如果有压痕的就写入压痕等

            string keyWord = string.Empty;
            if (product.Remark.Contains("淋"))
            {
                keyWord = "淋膜";
            }
            if (product.Remark.Contains("压"))
            {
                keyWord += ",压痕";
            }
            table.Rows.Add(new string[] { product.OrderName, product.CtmName, product.OrderCode, product.ShopName, product.PhotoNum.ToString(), product.PaperTypeName, product.PaperFaceName, keyWord }); ;

            XmlDocument doc = new XmlDocument();
            table.WriteXml(@"C:\Windows\xmldata\扩印小票.xml", XmlWriteMode.WriteSchema);
            report.Load(Application.StartupPath + "\\扩印小票.frx");
            //report.Show();
            report.Print();
        }


        internal Printer_Info GetPrinterInfo(int printerId)
        {
            return _bll.GetPrinterObj(printerId);
        }

        private PrinterConfigInfo GetPrinterConfigInfo(int printerId)
        {
            PrintConfigBLL bll = new PrintConfigBLL();
            return bll.GetPrinterConfigInfo(printerId);
        }

        internal void ExPortOrderFloderPic()
        {
            if (string.IsNullOrEmpty(DataTransfer.StrReportDir))
            {
                MessageBox.Show("没有设定扩印机的默认文件夹，请先设定！");
                return;
            }

            if (!Directory.Exists(DataTransfer.StrReportDir))
            {
                MessageBox.Show("请确认扩印机的默认文件夹能正常访问，然后再试！");
                return;
            }

            StartExportFloder();
        }

        /// <summary>
        /// 开如导出文件夹，但不包括backup文件夹
        /// </summary>
        private void StartExportFloder()
        {
            if (_curTaskList == null)
            {
                MessageBox.Show("没有选择任何产品！");
                return;
            }
            List<ProductView> selectProduct = _curTaskList.Where(o => o.IsSelect).ToList();
            if (selectProduct.Count < 1)
            {
                MessageBox.Show("没有选择任何产品！");
                return;
            }

            FrmMovePic frmMsg = new FrmMovePic();
            frmMsg.TotalPhotoNum = selectProduct.Sum(o => o.Photos.Count);
            frmMsg.Show();

            foreach (var oiTask in selectProduct)
            {
                string strTarGetOrderPath = DataTransfer.StrReportDir + "\\" + oiTask.OrderCode + "_" + oiTask.ShopName + "_" + oiTask.OrderName;
                if (!Directory.Exists(strTarGetOrderPath))
                {
                    Directory.CreateDirectory(strTarGetOrderPath);

                }
                else
                {
                    if (DialogResult.No == MessageBox.Show("该定单产品的目录已存在是否要覆盖？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                    {
                        continue;
                    }
                }

                //然后移图片
                //bool CopyOk = MovePic(oiTask.Photos, strTarGetOrderPath);
                bool CopyOk = MoveFolder(oiTask.Photos, strTarGetOrderPath);
                oiTask.Status = 1;
            }
            frmMsg.Close();
            MessageBox.Show("导出成功！");
        }

        /// <summary>
        /// 移动照片但按照照片备注中写的路径的目录名进行建目录
        /// </summary>
        /// <param name="list"></param>
        /// <param name="strTarGetOrderPath"></param>
        /// <returns></returns>
        private bool MoveFolder(List<PhotoInfo_Info> photoS, string tarGetPath)
        {
            bool result = true;
            foreach (var photo in photoS)
            {
                string picDir = string.Empty;//每一张图片的目录是根据在备注中的目录结构进行组后的

                picDir = GetPicExportDir(photo, tarGetPath);
                try
                {
                    if (!Directory.Exists(picDir))
                    {
                        Directory.CreateDirectory(picDir);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("在创建目录录录{0}时出错，请手动创建！\n" + ex.Message, tarGetPath));
                    result = false;
                    break;
                }

                FileInfo fi = new FileInfo(photo.PicPath);
                try
                {
                    fi.CopyTo(picDir + "\\" + fi.Name, true);
                    string newName = fi.Name.Substring(0, fi.Name.IndexOf(fi.Extension));
                    if (DataTransfer.MoveByPhotoNum)
                    {
                        for (int i = 1; i < photo.TotalNum; i++)
                        {
                            fi.CopyTo(picDir + "\\" + newName + "(" + i.ToString() + ")" + fi.Extension, true);
                        }
                    }
                }
                catch (Exception)
                {
                    ShowMsgEvent(photo.PicPath, false);
                    MessageBox.Show("移动图片" + fi.FullName + "时出错，请手动拷贝!");
                    result = false;

                    break;
                }
                finally
                {
                    fi = null;
                }
                ShowMsgEvent(photo.PicPath, true);
            }
            return result;
        }

        /// <summary>
        /// 根据照片备注里面的目录结构组合照片应放的目录结构
        /// </summary>
        /// <param name="pi"></param>
        /// <param name="tarGetPath">要导出的总目录</param>
        /// <returns></returns>
        private string GetPicExportDir(PhotoInfo_Info pi, string tarGetPath)
        {
            //photo的remark的结构如下:客人\产品\自定义文件夹名1\F2\a.jpg
            if (string.IsNullOrEmpty(pi.Remark))
            {
                return tarGetPath;
            }
            if (pi.Remark.IndexOf("\\") < 0)
            {
                return tarGetPath;
            }
            string strOrderProductNamePath = pi.Remark.Substring(pi.Remark.IndexOf("\\") + 1);//得到产品\自定义文件夹名1\F2\a.jpg
            if (strOrderProductNamePath.IndexOf("\\") <= 0)
            {
                return tarGetPath;
            }
            string resultPath = strOrderProductNamePath.Substring(strOrderProductNamePath.IndexOf("\\"));
            //得到 \自定义文件夹名1\F2\a.jpg
            //最后要得到目录
            int index = resultPath.LastIndexOf("\\");
            if (index <= 0)//说明总目录结构如下：客人\产品\a.jpg
            {
                return tarGetPath;
            }
            else
            {
                resultPath = tarGetPath + resultPath.Substring(0, resultPath.LastIndexOf("\\"));
                //得到 tarGetPath\自定义文件夹名1\F2

                return resultPath;
            }

        }


        /// <summary>
        /// 检查目录下面有没有end.txt文件,有就返回TRUE，否则返回False，如果文件夹不存在也返回false
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        private bool CheckFolderHasEndtxt(ProductView product)
        {
            if (Directory.Exists(product.OrderPath))
            {
                DirectoryInfo di = new DirectoryInfo(product.OrderPath);
                if (di.GetFiles("*.txt").FirstOrDefault(f => f.Name.Contains("end")) == null)
                    return true;
            }

            return false;
        }
    }
}
